import 'package:flutter/material.dart';

class Dropdown<T> extends StatefulWidget {
  final T? initialValue;
  final String hintText;
  final double? fontSize;
  final Color? fontColor;
  final Color? dropdownColor;
  final Widget icon;
  final List<DropdownMenuItem<T>> options;
  final void Function(T? value)? onChanged;

  const Dropdown({
    super.key,
    this.initialValue,
    this.hintText = '请输入',
    this.fontSize,
    this.fontColor,
    this.dropdownColor,
    this.icon = const Icon(Icons.keyboard_arrow_down, color: Colors.white24),
    this.onChanged,
    required this.options,
  });

  @override
  State<Dropdown<T>> createState() => _DropdownState<T>();
}

class _DropdownState<T> extends State<Dropdown<T>> {
  T? _value;

  // T? get value => _value ??= widget.initialValue;

  @override
  Widget build(BuildContext context) {
    T? value = _value ?? widget.initialValue;
    value = widget.options.where((element) => element.value == value).isEmpty ? null : value;
    return DropdownButtonHideUnderline(
      child: DropdownButton<T>(
        value: value,
        items: widget.options,
        onChanged: (T? value) {
          setState(() => _value = value);
          widget.onChanged?.call(_value);
        },
        isDense: true,
        isExpanded: true,
        elevation: 0,
        alignment: Alignment.centerLeft,
        icon: widget.icon,
        style: TextStyle(fontSize: widget.fontSize, height: 1.25, color: widget.fontColor, overflow: TextOverflow.ellipsis),
        dropdownColor: widget.dropdownColor,
        hint: Text(widget.hintText, style: TextStyle(color: widget.fontColor?.withOpacity(.5))),
        padding: EdgeInsets.zero,
      ),
    );
  }
}
